// additionalStrategies.js - 存放从index.vue中提取的额外策略函数
import axios from 'axios'
import { calculateVWAP } from './vwapStrategies.js'

// 计算移动平均线
export const calculateMA = (data, period) => {
  const ma = []
  for (let i = period - 1; i < data.length; i++) {
    let sum = 0
    for (let j = 0; j < period; j++) {
      sum += data[i - j].close
    }
    ma.push(sum / period)
  }
  return ma
}

// 计算RSI
export const calculateRSI = (data, period) => {
  if (data.length < period + 1) return []
  
  const rsi = []
  const gains = []
  const losses = []
  
  // 计算每日涨跌
  for (let i = 1; i < data.length; i++) {
    const change = data[i].close - data[i-1].close
    gains.push(change > 0 ? change : 0)
    losses.push(change < 0 ? Math.abs(change) : 0)
  }
  
  // 计算初始平均值
  let avgGain = gains.slice(0, period).reduce((a, b) => a + b, 0) / period
  let avgLoss = losses.slice(0, period).reduce((a, b) => a + b, 0) / period
  
  for (let i = period; i < gains.length; i++) {
    const rs = avgLoss === 0 ? 100 : avgGain / avgLoss
    const rsiValue = 100 - (100 / (1 + rs))
    rsi.push(rsiValue)
    
    // 更新平均值（使用指数平滑）
    avgGain = (avgGain * (period - 1) + gains[i]) / period
    avgLoss = (avgLoss * (period - 1) + losses[i]) / period
  }
  
  return rsi
}

// 计算布林带
export const calculateBollingerBands = (data, period, stdDevMultiplier) => {
  if (data.length < period) return []
  
  const bands = []
  
  for (let i = period - 1; i < data.length; i++) {
    // 计算中轨（移动平均线）
    let sum = 0
    for (let j = 0; j < period; j++) {
      sum += data[i - j].close
    }
    const middle = sum / period
    
    // 计算标准差
    let variance = 0
    for (let j = 0; j < period; j++) {
      const diff = data[i - j].close - middle
      variance += diff * diff
    }
    const stdDev = Math.sqrt(variance / period)
    
    // 计算上下轨
    const upper = middle + (stdDev * stdDevMultiplier)
    const lower = middle - (stdDev * stdDevMultiplier)
    
    bands.push({ upper, middle, lower })
  }
  
  return bands
}

// MA交叉策略
export const runMACrossStrategy = (data, settings) => {
  const results = {
    equityCurve: [],
    trades: []
  }
  
  const fastMA = settings.fastMAPeriod
  const slowMA = settings.slowMAPeriod
  const capital = settings.initialCapital
  const tradePercent = settings.tradeAmount / 100
  const stopLoss = settings.stopLoss / 100
  const takeProfit = settings.takeProfit / 100
  
  let position = 0 // 持仓数量
  let cash = capital // 现金
  let lastBuyPrice = 0
  
  // 计算MA
  const fastMAs = calculateMA(data, fastMA)
  const slowMAs = calculateMA(data, slowMA)
  
  // 确保有足够的数据计算MA
  if (fastMAs.length === 0 || slowMAs.length === 0) {
    console.warn('MA计算失败，数据不足')
    return results
  }
  
  for (let i = 1; i < Math.min(fastMAs.length, slowMAs.length); i++) {
    const dataIndex = i + slowMA - 1
    if (dataIndex >= data.length) break
    
    const currentPrice = data[dataIndex].close
    const currentDate = data[dataIndex].date
    
    // 检查交易信号
    const buySignal = fastMAs[i] > slowMAs[i] && fastMAs[i-1] <= slowMAs[i-1]
    const sellSignal = fastMAs[i] < slowMAs[i] && fastMAs[i-1] >= slowMAs[i-1]
    
    // 检查止损止盈
    const stopLossTriggered = position > 0 && currentPrice <= lastBuyPrice * (1 - stopLoss)
    const takeProfitTriggered = position > 0 && currentPrice >= lastBuyPrice * (1 + takeProfit)
    
    if (buySignal && position === 0 && cash > 0) {
      // 买入
      const tradeValue = cash * tradePercent
      const amount = tradeValue / currentPrice
      position = amount
      cash -= tradeValue
      lastBuyPrice = currentPrice
      
      results.trades.push({
        date: currentDate,
        type: 'buy',
        price: currentPrice,
        amount: amount,
        value: tradeValue
      })
    } else if ((sellSignal || stopLossTriggered || takeProfitTriggered) && position > 0) {
      // 卖出
      const sellAmount = position
      const tradeValue = sellAmount * currentPrice
      const profit = tradeValue - (sellAmount * lastBuyPrice)
      cash += tradeValue
      position = 0
      
      results.trades.push({
        date: currentDate,
        type: 'sell',
        price: currentPrice,
        amount: sellAmount,
        value: tradeValue,
        profit: profit
      })
    }
    
    // 更新权益曲线
    const totalEquity = cash + (position * currentPrice)
    results.equityCurve.push({
      date: currentDate,
      equity: totalEquity
    })
  }
  
  return results
}

// RSI策略
export const runRSIStrategy = (data, settings) => {
  const results = {
    equityCurve: [],
    trades: []
  }
  
  const capital = settings.initialCapital
  const tradePercent = settings.tradeAmount / 100
  const rsiPeriod = settings.rsiPeriod
  const overbought = settings.overbought
  const oversold = settings.oversold
  const stopLoss = settings.stopLoss / 100
  const takeProfit = settings.takeProfit / 100
  
  let position = 0
  let cash = capital
  let lastBuyPrice = 0
  
  // 计算RSI
  const rsiValues = calculateRSI(data, rsiPeriod)
  
  if (rsiValues.length === 0) {
    console.warn('RSI计算失败，数据不足')
    return results
  }
  
  for (let i = 1; i < rsiValues.length; i++) {
    const dataIndex = i + rsiPeriod
    if (dataIndex >= data.length) break
    
    const currentPrice = data[dataIndex].close
    const currentDate = data[dataIndex].date
    const currentRSI = rsiValues[i]
    const prevRSI = rsiValues[i-1]
    
    // RSI交易信号
    const buySignal = prevRSI <= oversold && currentRSI > oversold && position === 0
    const sellSignal = prevRSI >= overbought && currentRSI < overbought && position > 0
    
    // 检查止损止盈
    const stopLossTriggered = position > 0 && currentPrice <= lastBuyPrice * (1 - stopLoss)
    const takeProfitTriggered = position > 0 && currentPrice >= lastBuyPrice * (1 + takeProfit)
    
    if (buySignal && cash > 0) {
      // 买入
      const tradeValue = cash * tradePercent
      const amount = tradeValue / currentPrice
      position = amount
      cash -= tradeValue
      lastBuyPrice = currentPrice
      
      results.trades.push({
        date: currentDate,
        type: 'buy',
        price: currentPrice,
        amount: amount,
        value: tradeValue
      })
    } else if ((sellSignal || stopLossTriggered || takeProfitTriggered) && position > 0) {
      // 卖出
      const sellAmount = position
      const tradeValue = sellAmount * currentPrice
      const profit = tradeValue - (sellAmount * lastBuyPrice)
      cash += tradeValue
      position = 0
      
      results.trades.push({
        date: currentDate,
        type: 'sell',
        price: currentPrice,
        amount: sellAmount,
        value: tradeValue,
        profit: profit
      })
    }
    
    // 更新权益曲线
    const totalEquity = cash + (position * currentPrice)
    results.equityCurve.push({
      date: currentDate,
      equity: totalEquity
    })
  }
  
  return results
}

// 布林带策略
export const runBollingerStrategy = (data, settings) => {
  const results = {
    equityCurve: [],
    trades: []
  }
  
  const capital = settings.initialCapital
  const tradePercent = settings.tradeAmount / 100
  const bbPeriod = settings.bbPeriod
  const bbStdDev = settings.bbStdDev
  const stopLoss = settings.stopLoss / 100
  const takeProfit = settings.takeProfit / 100
  
  let position = 0
  let cash = capital
  let lastBuyPrice = 0
  
  // 计算布林带
  const bollingerBands = calculateBollingerBands(data, bbPeriod, bbStdDev)
  
  if (bollingerBands.length === 0) {
    console.warn('布林带计算失败，数据不足')
    return results
  }
  
  for (let i = 0; i < bollingerBands.length; i++) {
    const dataIndex = i + bbPeriod - 1
    if (dataIndex >= data.length) break
    
    const currentPrice = data[dataIndex].close
    const currentDate = data[dataIndex].date
    const { upper, lower, middle } = bollingerBands[i]
    
    // 布林带交易信号
    const buySignal = currentPrice <= lower && position === 0  // 价格触及下轨
    const sellSignal = currentPrice >= upper && position > 0   // 价格触及上轨
    
    // 检查止损止盈
    const stopLossTriggered = position > 0 && currentPrice <= lastBuyPrice * (1 - stopLoss)
    const takeProfitTriggered = position > 0 && currentPrice >= lastBuyPrice * (1 + takeProfit)
    
    if (buySignal && cash > 0) {
      // 买入
      const tradeValue = cash * tradePercent
      const amount = tradeValue / currentPrice
      position = amount
      cash -= tradeValue
      lastBuyPrice = currentPrice
      
      results.trades.push({
        date: currentDate,
        type: 'buy',
        price: currentPrice,
        amount: amount,
        value: tradeValue
      })
    } else if ((sellSignal || stopLossTriggered || takeProfitTriggered) && position > 0) {
      // 卖出
      const sellAmount = position
      const tradeValue = sellAmount * currentPrice
      const profit = tradeValue - (sellAmount * lastBuyPrice)
      cash += tradeValue
      position = 0
      
      results.trades.push({
        date: currentDate,
        type: 'sell',
        price: currentPrice,
        amount: sellAmount,
        value: tradeValue,
        profit: profit
      })
    }
    
    // 更新权益曲线
    const totalEquity = cash + (position * currentPrice)
    results.equityCurve.push({
      date: currentDate,
      equity: totalEquity
    })
  }
  
  return results
}

// 自定义策略
export const runCustomStrategy = (data, settings) => {
  const results = {
    equityCurve: [],
    trades: []
  }
  
  const capital = settings.initialCapital
  const tradePercent = settings.tradeAmount / 100
  const stopLoss = settings.stopLoss / 100
  const takeProfit = settings.takeProfit / 100
  
  let position = 0
  let cash = capital
  let lastBuyPrice = 0
  
  // 简单的动量 + 价格突破策略
  for (let i = 5; i < data.length; i++) {
    const currentPrice = data[i].close
    const currentDate = data[i].date
    const currentVolume = data[i].volume
    
    // 计算近5日平均价格和成交量
    const avgPrice = data.slice(i-5, i).reduce((sum, d) => sum + d.close, 0) / 5
    const avgVolume = data.slice(i-5, i).reduce((sum, d) => sum + d.volume, 0) / 5
    
    // 交易信号：价格突破平均线 + 成交量放大
    const priceBreakout = currentPrice > avgPrice * 1.02 // 价格突破上方2%
    const volumeSpike = currentVolume > avgVolume * 1.5  // 成交量放大1.5倍
    const buySignal = priceBreakout && volumeSpike && position === 0
    
    const priceDrop = currentPrice < avgPrice * 0.98    // 价格跌破下方2%
    const sellSignal = priceDrop && position > 0
    
    // 检查止损止盈
    const stopLossTriggered = position > 0 && currentPrice <= lastBuyPrice * (1 - stopLoss)
    const takeProfitTriggered = position > 0 && currentPrice >= lastBuyPrice * (1 + takeProfit)
    
    if (buySignal && cash > 0) {
      // 买入
      const tradeValue = cash * tradePercent
      const amount = tradeValue / currentPrice
      position = amount
      cash -= tradeValue
      lastBuyPrice = currentPrice
      
      results.trades.push({
        date: currentDate,
        type: 'buy',
        price: currentPrice,
        amount: amount,
        value: tradeValue
      })
    } else if ((sellSignal || stopLossTriggered || takeProfitTriggered) && position > 0) {
      // 卖出
      const sellAmount = position
      const tradeValue = sellAmount * currentPrice
      const profit = tradeValue - (sellAmount * lastBuyPrice)
      cash += tradeValue
      position = 0
      
      results.trades.push({
        date: currentDate,
        type: 'sell',
        price: currentPrice,
        amount: sellAmount,
        value: tradeValue,
        profit: profit
      })
    }
    
    // 更新权益曲线
    const totalEquity = cash + (position * currentPrice)
    results.equityCurve.push({
      date: currentDate,
      equity: totalEquity
    })
  }
  
  return results
}

// VWAP策略
export const runVWAPStrategy = (data, settings) => {
  try {
    console.log('开始执行VWAP策略回测')
    
    const results = {
      equityCurve: [],
      trades: []
    }
    
    // 参数验证
    if (!data || !Array.isArray(data) || data.length === 0) {
      console.warn('VWAP策略回测失败：输入数据为空或无效')
      return results
    }
    
    const capital = settings.initialCapital
    const tradePercent = settings.tradeAmount / 100
    const stopLoss = settings.stopLoss / 100
    const takeProfit = settings.takeProfit / 100
    
    // 参数有效性检查
    if (capital <= 0 || tradePercent <= 0 || tradePercent > 1) {
      console.warn('VWAP策略回测参数无效')
      return results
    }
    
    console.log(`VWAP策略参数：初始资金${capital}，交易比例${tradePercent}，止损${stopLoss}，止盈${takeProfit}`)
    
    let position = 0
    let cash = capital
    let lastBuyPrice = 0
    
    // 计算VWAP
    console.log(`开始计算VWAP，输入数据${data.length}条`)
    const vwapValues = calculateVWAP(data)
    
    if (vwapValues.length === 0) {
      console.warn('VWAP计算失败，数据不足')
      return results
    }
    
    console.log(`VWAP计算完成，得到${vwapValues.length}条VWAP数据`)
    
    let validSignals = 0
    let buySignals = 0
    let sellSignals = 0
    
    for (let i = 1; i < vwapValues.length; i++) {
      const dataIndex = i
      if (dataIndex >= data.length) {
        console.warn(`数据索引超出范围：${dataIndex} >= ${data.length}`)
        break
      }
      
      // 检查数据完整性
      if (!data[dataIndex] || data[dataIndex].close === undefined || 
          data[dataIndex].date === undefined) {
        console.warn(`索引${dataIndex}处的数据不完整`)
        continue
      }
      
      const currentPrice = data[dataIndex].close
      const currentDate = data[dataIndex].date
      const currentVWAP = vwapValues[i]
      const prevVWAP = vwapValues[i-1]
      
      // 打印VWAP参数
      console.log(`VWAP策略参数[${dataIndex}] - 日期: ${currentDate}, 当前价格: ${currentPrice.toFixed(4)}, 当前VWAP: ${currentVWAP.toFixed(4)}, 前一个VWAP: ${prevVWAP.toFixed(4)}, 持仓: ${position}, 现金: ${cash.toFixed(2)}`)
      
      // 检查数值有效性
      if (!isFinite(currentPrice) || !isFinite(currentVWAP) || !isFinite(prevVWAP)) {
        console.warn(`索引${dataIndex}处的价格或VWAP值无效`)
        continue
      }
      
      // VWAP交易信号
      // 买入信号：当前价格上穿VWAP线 且 前一个VWAP值大于等于当前VWAP值 且 当前无持仓
      const buySignal = currentPrice > currentVWAP && prevVWAP >= currentVWAP && position === 0
      // 卖出信号：当前价格下穿VWAP线 且 前一个VWAP值小于等于当前VWAP值 且 当前有持仓
      const sellSignal = currentPrice < currentVWAP && prevVWAP <= currentVWAP && position > 0
      
      // 检查止损止盈
      const stopLossTriggered = position > 0 && currentPrice <= lastBuyPrice * (1 - stopLoss)
      const takeProfitTriggered = position > 0 && currentPrice >= lastBuyPrice * (1 + takeProfit)
      
      if (buySignal && cash > 0) {
        validSignals++
        buySignals++
        console.log(`生成买入信号 - 日期: ${currentDate}, 价格: ${currentPrice}, VWAP: ${currentVWAP}`)
        
        // 买入
        const tradeValue = cash * tradePercent
        const amount = tradeValue / currentPrice
        position = amount
        cash -= tradeValue
        lastBuyPrice = currentPrice
        
        console.log(`执行买入 - 金额: ${tradeValue}, 数量: ${amount}, 剩余资金: ${cash}`)
        
        results.trades.push({
          date: currentDate,
          type: 'buy',
          price: currentPrice,
          amount: amount,
          value: tradeValue,
          reason: '价格上穿VWAP'
        })
      } else if ((sellSignal || stopLossTriggered || takeProfitTriggered) && position > 0) {
        validSignals++
        sellSignals++
        
        const signalType = stopLossTriggered ? '止损' : 
                          takeProfitTriggered ? '止盈' : 
                          '价格下穿VWAP'
        console.log(`生成卖出信号 - 日期: ${currentDate}, 价格: ${currentPrice}, VWAP: ${currentVWAP}, 类型: ${signalType}`)
        
        // 卖出
        const sellAmount = position
        const tradeValue = sellAmount * currentPrice
        const profit = tradeValue - (sellAmount * lastBuyPrice)
        cash += tradeValue
        position = 0
        
        console.log(`执行卖出 - 金额: ${tradeValue}, 利润: ${profit}, 总资金: ${cash}`)
        
        const sellReason = stopLossTriggered ? '止损' : 
                          takeProfitTriggered ? '止盈' : 
                          '价格下穿VWAP'
        
        results.trades.push({
          date: currentDate,
          type: 'sell',
          price: currentPrice,
          amount: sellAmount,
          value: tradeValue,
          profit: profit,
          reason: sellReason
        })
      }
      
      // 更新权益曲线
      const totalEquity = cash + (position * currentPrice)
      results.equityCurve.push({
        date: currentDate,
        equity: totalEquity
      })
    }
    
    console.log(`VWAP策略回测完成：总共${validSignals}个有效信号，买入${buySignals}次，卖出${sellSignals}次`)
    console.log(`最终结果：现金${cash}，持仓${position}，总权益${cash + (position * (data.length > 0 ? data[data.length-1].close : 0))}`)
    
    return results
  } catch (error) {
    console.error('VWAP策略回测过程中发生错误：', error)
    return {
      equityCurve: [],
      trades: []
    }
  }
}

// AI智能策略1 - 基于机器学习的多因子量化交易策略（优化版）
export const runMLStrategy1 = (data, settings) => {
  const results = {
    equityCurve: [],
    trades: [],
    signals: [], // 新增：记录信号强度
    performance: {} // 新增：性能指标
  }
  
  const capital = settings.initialCapital
  const baseTradePercent = settings.tradeAmount / 100
  
  let position = 0
  let cash = capital
  let lastBuyPrice = 0
  let marketState = 'neutral'
  let consecutiveLosses = 0 // 新增：连续亏损计数
  let maxEquity = capital // 新增：最高权益记录
  
  const minDataPoints = Math.max(100, data.length * 0.15) // 优化：增加最小数据点
  
  for (let i = Math.floor(minDataPoints); i < data.length; i++) {
    const currentPrice = data[i].close
    const currentDate = data[i].date
    
    const features = calculateMLFeatures(data, i)
    if (!features) continue
    
    if (settings.mlMarketStateAware) {
      marketState = identifyMarketState(data, i)
    }
    
    const mlPrediction = performMLPrediction(features, marketState, settings)
    
    // 记录信号强度用于分析
    results.signals.push({
      date: currentDate,
      signal: mlPrediction.signal,
      confidence: mlPrediction.confidence,
      marketState: marketState,
      price: currentPrice
    })
    
    let dynamicTradePercent = baseTradePercent
    if (settings.mlDynamicPositioning) {
      dynamicTradePercent = calculateDynamicPosition(features, mlPrediction, baseTradePercent, consecutiveLosses)
    }
    
    const adaptiveStopLoss = calculateAdaptiveStopLoss(features.atr, settings.mlAdaptiveStopLoss)
    const adaptiveTakeProfit = calculateAdaptiveTakeProfit(features.atr, mlPrediction.confidence)
    
    // 优化：添加风险过滤器
    const riskFilter = evaluateRiskConditions(features, marketState, consecutiveLosses, cash, capital)
    
    const buySignal = mlPrediction.signal === 'buy' && 
                     mlPrediction.confidence >= settings.mlConfidenceThreshold && 
                     position === 0 && 
                     riskFilter.allowBuy // 新增风险过滤
  
    const sellSignal = (mlPrediction.signal === 'sell' && 
                       mlPrediction.confidence >= settings.mlConfidenceThreshold) ||
                      checkMLStopConditions(currentPrice, lastBuyPrice, adaptiveStopLoss, adaptiveTakeProfit) ||
                      riskFilter.forceSell // 新增强制卖出条件
  
    if (buySignal && cash > 0) {
      const tradeValue = cash * (dynamicTradePercent / 100)
      const amount = tradeValue / currentPrice
      position = amount
      cash -= tradeValue
      lastBuyPrice = currentPrice
      consecutiveLosses = 0 // 重置连续亏损计数
      
      results.trades.push({
        date: currentDate,
        type: 'buy',
        price: currentPrice,
        amount: amount,
        value: tradeValue,
        reason: `ML信号(置信度:${(mlPrediction.confidence * 100).toFixed(1)}%,市场:${marketState},动态仓位:${dynamicTradePercent.toFixed(1)}%)`
      })
    } else if (sellSignal && position > 0) {
      const sellAmount = position
      const tradeValue = sellAmount * currentPrice
      const profit = tradeValue - (sellAmount * lastBuyPrice)
      cash += tradeValue
      position = 0
      
      // 更新连续亏损计数
      if (profit < 0) {
        consecutiveLosses++
      } else {
        consecutiveLosses = 0
      }
      
      const sellReason = mlPrediction.signal === 'sell' ? 
        `ML卖出信号(置信度:${(mlPrediction.confidence * 100).toFixed(1)}%)` :
        riskFilter && riskFilter.forceSell ? '风险控制强制卖出' :
        `智能止损止盈(ATR:${features.atr.toFixed(2)})`
      
      results.trades.push({
        date: currentDate,
        type: 'sell',
        price: currentPrice,
        amount: sellAmount,
        value: tradeValue,
        profit: profit,
        reason: sellReason
      })
    }
    
    const totalEquity = cash + (position * currentPrice)
    
    // 更新最高权益
    if (totalEquity > maxEquity) {
      maxEquity = totalEquity
    }
    
    results.equityCurve.push({
      date: currentDate,
      equity: totalEquity,
      drawdown: ((maxEquity - totalEquity) / maxEquity * 100).toFixed(2) // 记录回撤
    })
  }
  
  // 计算策略性能指标
  results.performance = calculateStrategyPerformance(results)
  
  return results
}

// ML特征计算函数
const calculateMLFeatures = (data, index) => {
  if (index < 50) return null
  
  const currentData = data.slice(Math.max(0, index - 49), index + 1)
  const prices = currentData.map(d => d.close)
  const volumes = currentData.map(d => d.volume)
  const highs = currentData.map(d => d.high)
  const lows = currentData.map(d => d.low)
  
  const ma5 = calculateSMA(prices, 5)
  const ma10 = calculateSMA(prices, 10)
  const ma20 = calculateSMA(prices, 20)
  const ma50 = calculateSMA(prices, 50)
  
  const rsi = calculateRSI(currentData, 14)
  const macd = calculateMACD(prices)
  const bb = calculateBB(prices, 20, 2)
  const atr = calculateATR(currentData, 14)
  
  const volumeMA = calculateSMA(volumes, 20)
  const volumeRatio = volumes[volumes.length - 1] / (volumeMA[volumeMA.length - 1] || 1)
  
  const momentum = (prices[prices.length - 1] - prices[prices.length - 10]) / prices[prices.length - 10]
  const volatility = calculateVolatility(prices, 20)
  const supportResistance = calculateSupportResistance(currentData)
  
  return {
    price: prices[prices.length - 1],
    ma5: ma5[ma5.length - 1],
    ma10: ma10[ma10.length - 1],
    ma20: ma20[ma20.length - 1],
    ma50: ma50[ma50.length - 1],
    rsi: rsi[rsi.length - 1],
    macd_line: macd.macd[macd.macd.length - 1],
    macd_signal: macd.signal[macd.signal.length - 1],
    macd_histogram: macd.histogram[macd.histogram.length - 1],
    bb_upper: bb.upper[bb.upper.length - 1],
    bb_middle: bb.middle[bb.middle.length - 1],
    bb_lower: bb.lower[bb.lower.length - 1],
    atr: atr[atr.length - 1],
    volume_ratio: volumeRatio,
    momentum: momentum,
    volatility: volatility,
    support: supportResistance.support,
    resistance: supportResistance.resistance
  }
}

// ML辅助函数（简化实现）
const calculateSMA = (data, period) => {
  const result = []
  for (let i = period - 1; i < data.length; i++) {
    let sum = 0
    for (let j = 0; j < period; j++) {
      sum += data[i - j]
    }
    result.push(sum / period)
  }
  return result
}

const calculateMACD = (prices) => {
  const ema12 = calculateEMA(prices, 12)
  const ema26 = calculateEMA(prices, 26)
  const macd = ema12.map((val, i) => val - ema26[i])
  const signal = calculateEMA(macd, 9)
  
  return {
    macd: macd,
    signal: signal,
    histogram: macd.map((val, i) => val - signal[i])
  }
}

const calculateEMA = (data, period) => {
  const result = []
  const multiplier = 2 / (period + 1)
  
  for (let i = 0; i < data.length; i++) {
    if (i === 0) {
      result.push(data[i])
    } else {
      result.push((data[i] - result[i - 1]) * multiplier + result[i - 1])
    }
  }
  
  return result
}

const calculateBB = (prices, period, stdDevMultiplier) => {
  const result = []
  
  for (let i = period - 1; i < prices.length; i++) {
    // 计算中轨（移动平均线）
    let sum = 0
    for (let j = 0; j < period; j++) {
      sum += prices[i - j]
    }
    const middle = sum / period
    
    // 计算标准差
    let variance = 0
    for (let j = 0; j < period; j++) {
      const diff = prices[i - j] - middle
      variance += diff * diff
    }
    const stdDev = Math.sqrt(variance / period)
    
    // 计算上下轨
    const upper = middle + (stdDev * stdDevMultiplier)
    const lower = middle - (stdDev * stdDevMultiplier)
    
    result.push({ upper, middle, lower })
  }
  
  return result
}

const calculateATR = (data, period) => {
  const tr = []
  
  for (let i = 1; i < data.length; i++) {
    const high = data[i].high
    const low = data[i].low
    const close = data[i].close
    const prevClose = data[i - 1].close
    
    const tr1 = high - low
    const tr2 = Math.abs(high - prevClose)
    const tr3 = Math.abs(low - prevClose)
    
    tr.push(Math.max(tr1, tr2, tr3))
  }
  
  return calculateSMA(tr, period)
}

const calculateVolatility = (prices, period) => {
  const logReturns = []
  
  for (let i = 1; i < prices.length; i++) {
    const logReturn = Math.log(prices[i] / prices[i - 1])
    logReturns.push(logReturn)
  }
  
  const variance = logReturns.reduce((sum, val) => sum + val * val, 0) / logReturns.length
  return Math.sqrt(variance) * Math.sqrt(period)
}

const calculateSupportResistance = (data) => {
  const prices = data.map(d => d.close)
  const highs = data.map(d => d.high)
  const lows = data.map(d => d.low)
  
  const support = Math.min(...lows)
  const resistance = Math.max(...highs)
  
  return { support, resistance }
}

const calculateTrendSlope = (prices) => {
  if (prices.length < 2) return 0
  
  let sumX = 0, sumY = 0, sumXY = 0, sumXX = 0
  const n = prices.length
  
  for (let i = 0; i < n; i++) {
    sumX += i
    sumY += prices[i]
    sumXY += i * prices[i]
    sumXX += i * i
  }
  
  const slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX)
  return slope / (sumY / n) // 标准化斜率
}

const identifyMarketState = (data, index) => {
  const lookback = Math.min(50, index)
  const recentData = data.slice(index - lookback + 1, index + 1)
  const prices = recentData.map(d => d.close)
  
  const trendSlope = calculateTrendSlope(prices)
  const volatility = calculateVolatility(prices, Math.min(20, prices.length))
  
  if (Math.abs(trendSlope) < 0.001 && volatility < 0.02) {
    return 'sideways'
  } else if (trendSlope > 0.002) {
    return 'bull'
  } else if (trendSlope < -0.002) {
    return 'bear'
  } else {
    return 'neutral'
  }
}

// 优化：ML预测算法（增强版）
const performMLPrediction = (features, marketState, settings) => {
  const weights = getFeatureWeights(settings.mlFeatureWeighting)
  
  let buyScore = 0
  let sellScore = 0
  
  // 1. 趋势因子（增强版）
  const trendScore = calculateTrendScore(features)
  buyScore += trendScore.bullish * weights.trend
  sellScore += trendScore.bearish * weights.trend
  
  // 2. 动量因子（多层次）
  const momentumScore = calculateMomentumScore(features)
  buyScore += momentumScore.bullish * weights.momentum
  sellScore += momentumScore.bearish * weights.momentum
  
  // 3. 反转因子（精细化）
  const reversalScore = calculateReversalScore(features)
  buyScore += reversalScore.bullish * weights.reversal
  sellScore += reversalScore.bearish * weights.reversal
  
  // 4. 成交量因子（新增）
  const volumeScore = calculateVolumeScore(features)
  buyScore += volumeScore.bullish * weights.volume
  sellScore += volumeScore.bearish * weights.volume
  
  // 5. 波动性因子（新增）
  const volatilityScore = calculateVolatilityScore(features)
  buyScore += volatilityScore.adjustment
  sellScore -= volatilityScore.adjustment
  
  // 6. 市场状态调整（优化）
  const stateMultiplier = getMarketStateMultiplier(marketState, features)
  buyScore *= stateMultiplier.buy
  sellScore *= stateMultiplier.sell
  
  // 7. 情绪指标调整（增强）
  const sentimentFactor = calculateAdvancedSentimentIndicator(features, marketState)
  buyScore += sentimentFactor * settings.mlSentimentWeight
  sellScore -= sentimentFactor * settings.mlSentimentWeight
  
  // 8. 正则化评分（改进）
  const totalScore = Math.abs(buyScore) + Math.abs(sellScore)
  let normalizedBuyScore = totalScore > 0 ? Math.abs(buyScore) / totalScore : 0.5
  let normalizedSellScore = totalScore > 0 ? Math.abs(sellScore) / totalScore : 0.5
  
  // 9. 信号筛选和置信度计算
  let signal = 'hold'
  let confidence = 0
  
  const signalThreshold = 0.55 // 降低阈值提高灵敏度
  const strongSignalThreshold = 0.7 // 强信号阈值
  
  if (normalizedBuyScore > signalThreshold && normalizedBuyScore > normalizedSellScore) {
    signal = 'buy'
    confidence = normalizedBuyScore
    // 强信号额外加分
    if (normalizedBuyScore > strongSignalThreshold) {
      confidence = Math.min(0.95, confidence * 1.1)
    }
  } else if (normalizedSellScore > signalThreshold && normalizedSellScore > normalizedBuyScore) {
    signal = 'sell'
    confidence = normalizedSellScore
    // 强信号额外加分
    if (normalizedSellScore > strongSignalThreshold) {
      confidence = Math.min(0.95, confidence * 1.1)
    }
  }
  
  return {
    signal,
    confidence,
    buyScore: normalizedBuyScore,
    sellScore: normalizedSellScore,
    marketState,
    details: { // 新增：详细信息
      trendScore,
      momentumScore,
      reversalScore,
      volumeScore,
      volatilityScore,
      sentimentFactor
    }
  }
}

// 新增：趋势评分算法
const calculateTrendScore = (features) => {
  let bullish = 0
  let bearish = 0
  
  // 多层MA分析
  const maAlignment = {
    short: features.price > features.ma5 ? 1 : -1,
    medium: features.ma5 > features.ma20 ? 1 : -1,
    long: features.ma20 > features.ma50 ? 1 : -1
  }
  
  // MA排列评分
  const alignmentScore = (maAlignment.short + maAlignment.medium + maAlignment.long) / 3
  if (alignmentScore > 0.33) bullish += 0.4
  if (alignmentScore < -0.33) bearish += 0.4
  
  // 价格位置分析
  const pricePosition = {
    aboveMA5: (features.price - features.ma5) / features.ma5,
    aboveMA20: (features.price - features.ma20) / features.ma20
  }
  
  if (pricePosition.aboveMA5 > 0.02) bullish += 0.3
  if (pricePosition.aboveMA5 < -0.02) bearish += 0.3
  if (pricePosition.aboveMA20 > 0.05) bullish += 0.3
  if (pricePosition.aboveMA20 < -0.05) bearish += 0.3
  
  return { bullish, bearish }
}

// 新增：动量评分算法
const calculateMomentumScore = (features) => {
  let bullish = 0
  let bearish = 0
  
  // 价格动量
  if (features.momentum > 0.03) bullish += 0.5
  else if (features.momentum > 0.01) bullish += 0.3
  if (features.momentum < -0.03) bearish += 0.5
  else if (features.momentum < -0.01) bearish += 0.3
  
  // RSI动量
  if (features.rsi < 25) bullish += 0.4
  else if (features.rsi < 35) bullish += 0.2
  if (features.rsi > 75) bearish += 0.4
  else if (features.rsi > 65) bearish += 0.2
  
  // MACD动量
  if (features.macd_line > features.macd_signal && features.macd_histogram > 0) bullish += 0.3
  if (features.macd_line < features.macd_signal && features.macd_histogram < 0) bearish += 0.3
  
  // MACD金叉死叉加分
  const macdCrossover = features.macd_histogram > 0 && Math.abs(features.macd_histogram) > Math.abs(features.macd_line) * 0.1
  if (macdCrossover && features.macd_line > 0) bullish += 0.2
  if (!macdCrossover && features.macd_line < 0) bearish += 0.2
  
  return { bullish, bearish }
}

// 新增：反转评分算法
const calculateReversalScore = (features) => {
  let bullish = 0
  let bearish = 0
  
  // 布林带位置
  const bbPosition = (features.price - features.bb_lower) / (features.bb_upper - features.bb_lower)
  if (bbPosition < 0.15) bullish += 0.6 // 接近下轨
  else if (bbPosition < 0.25) bullish += 0.3
  if (bbPosition > 0.85) bearish += 0.6 // 接近上轨
  else if (bbPosition > 0.75) bearish += 0.3
  
  // 支撑阻力分析
  const supportDistance = (features.price - features.support) / features.support
  const resistanceDistance = (features.resistance - features.price) / features.price
  
  if (supportDistance < 0.015) bullish += 0.4 // 靠近支撑
  if (resistanceDistance < 0.015) bearish += 0.4 // 靠近阻力
  
  // 极端指标值
  if (features.rsi < 15) bullish += 0.5 // 极度超卖
  if (features.rsi > 85) bearish += 0.5 // 极度超买
  
  return { bullish, bearish }
}

// 新增：成交量评分算法
const calculateVolumeScore = (features) => {
  let bullish = 0
  let bearish = 0
  
  // 成交量放大程度
  if (features.volume_ratio > 2.5) {
    bullish += 0.4 // 大量放大通常是看涨信号
  } else if (features.volume_ratio > 1.8) {
    bullish += 0.2
  } else if (features.volume_ratio < 0.5) {
    bearish += 0.2 // 成交量萝缩可能是下跌信号
  }
  
  // 成交量与价格变化的关系
  if (features.volume_ratio > 1.5 && features.momentum > 0) {
    bullish += 0.3 // 量价齐升
  }
  
  if (features.volume_ratio > 1.5 && features.momentum < 0) {
    bearish += 0.3 // 量增价跌
  }
  
  return { bullish, bearish }
}

// 新增：波动性评分算法
const calculateVolatilityScore = (features) => {
  let adjustment = 0
  
  // 波动性调整（低波动性适合交易，高波动性需谨慎）
  if (features.volatility < 0.015) {
    adjustment = 0.1 // 低波动性增加信心
  } else if (features.volatility > 0.08) {
    adjustment = -0.2 // 高波动性减少信心
  } else if (features.volatility > 0.05) {
    adjustment = -0.1
  }
  
  return { adjustment }
}

// 新增：市场状态乘数
const getMarketStateMultiplier = (marketState, features) => {
  switch (marketState) {
    case 'bull':
      return { buy: 1.3, sell: 0.7 }
    case 'bear':
      return { buy: 0.6, sell: 1.4 }
    case 'sideways':
      // 震荡市适合反转交易
      return features.rsi < 30 || features.rsi > 70 ? 
        { buy: 1.1, sell: 1.1 } : { buy: 0.9, sell: 0.9 }
    default:
      return { buy: 1.0, sell: 1.0 }
  }
}

// 优化：高级情绪指标
const calculateAdvancedSentimentIndicator = (features, marketState) => {
  let sentiment = 0
  
  // 1. 恐慌指数（VIX类似）
  const fearIndex = calculateFearIndex(features)
  if (fearIndex > 0.8) sentiment += 0.6 // 极度恐慌时反向买入
  else if (fearIndex > 0.6) sentiment += 0.3
  
  // 2. 贪婪指数
  const greedIndex = calculateGreedIndex(features)
  if (greedIndex > 0.8) sentiment -= 0.6 // 极度贪婪时谨慎
  else if (greedIndex > 0.6) sentiment -= 0.3
  
  // 3. 技术指标远离平衡
  const technicalExtreme = calculateTechnicalExtreme(features)
  sentiment += technicalExtreme * 0.4
  
  // 4. 市场状态调整
  if (marketState === 'bear' && sentiment > 0) {
    sentiment *= 1.2 // 熊市中的反转信号更强
  } else if (marketState === 'bull' && sentiment < 0) {
    sentiment *= 1.2 // 牛市中的顶部信号更强
  }
  
  return Math.max(-1, Math.min(1, sentiment))
}

// 恐慌指数计算
const calculateFearIndex = (features) => {
  let fearScore = 0
  
  // RSI极低值
  if (features.rsi < 20) fearScore += 0.4
  else if (features.rsi < 30) fearScore += 0.2
  
  // 价格远低于布林带下轨
  if (features.price < features.bb_lower * 0.98) fearScore += 0.3
  
  // 高波动性环境
  if (features.volatility > 0.06) fearScore += 0.3
  
  return Math.min(1, fearScore)
}

// 贪婪指数计算
const calculateGreedIndex = (features) => {
  let greedScore = 0
  
  // RSI极高值
  if (features.rsi > 80) greedScore += 0.4
  else if (features.rsi > 70) greedScore += 0.2
  
  // 价格远高于布林带上轨
  if (features.price > features.bb_upper * 1.02) greedScore += 0.3
  
  // 成交量异常放大
  if (features.volume_ratio > 3) greedScore += 0.3
  
  return Math.min(1, greedScore)
}

// 技术指标远离平衡
const calculateTechnicalExtreme = (features) => {
  let extremeScore = 0
  
  // 多个指标同时超买/超卖
  const oversoldCount = [
    features.rsi < 25,
    features.price < features.bb_lower,
    features.momentum < -0.05
  ].filter(Boolean).length
  
  const overboughtCount = [
    features.rsi > 75,
    features.price > features.bb_upper,
    features.momentum > 0.05
  ].filter(Boolean).length
  
  if (oversoldCount >= 2) extremeScore += 0.5
  if (overboughtCount >= 2) extremeScore -= 0.5
  
  return extremeScore
}

// 保留原有的getFeatureWeights函数（并优化）
const getFeatureWeights = (mode) => {
  switch (mode) {
    case 'trend_focused':
      return { trend: 0.5, momentum: 0.2, reversal: 0.2, volume: 0.1 }
    case 'momentum_focused':
      return { trend: 0.2, momentum: 0.5, reversal: 0.2, volume: 0.1 }
    case 'reversal_focused':
      return { trend: 0.2, momentum: 0.2, reversal: 0.5, volume: 0.1 }
    case 'balanced':
    default:
      return { trend: 0.3, momentum: 0.3, reversal: 0.3, volume: 0.1 }
  }
}

// 新增：风险评估函数
const evaluateRiskConditions = (features, marketState, consecutiveLosses, cash, initialCapital) => {
  let allowBuy = true
  let forceSell = false
  
  // 1. 连续亏损风险控制
  if (consecutiveLosses >= 3) {
    allowBuy = false // 连续3次亏损后暂停交易
  }
  
  // 2. 资金水位风险控制
  const remainingCapitalRatio = cash / initialCapital
  if (remainingCapitalRatio < 0.3) {
    allowBuy = false // 资金低于30%暂停交易
  }
  
  // 3. 极端市场环境风险控制
  if (features.volatility > 0.1 && marketState === 'bear') {
    allowBuy = false // 高波动性熊市环境下不交易
    forceSell = true // 强制清仓
  }
  
  // 4. 技术指标极端值风险控制
  if (features.rsi > 90 || features.rsi < 10) {
    if (features.rsi > 90) forceSell = true
    if (features.rsi < 10) allowBuy = false // 极度超卖时谨慎交易
  }
  
  return { allowBuy, forceSell }
}

// 优化：动态仓位管理函数（考虑连续亏损）
const calculateDynamicPosition = (features, prediction, basePercent, consecutiveLosses = 0) => {
  let positionMultiplier = 1
  
  // 基于置信度调整
  positionMultiplier *= prediction.confidence
  
  // 基于波动性调整
  if (features.volatility > 0.05) {
    positionMultiplier *= 0.6 // 更保守
  } else if (features.volatility < 0.02) {
    positionMultiplier *= 1.4 // 更激进
  }
  
  // 基于连续亏损调整
  if (consecutiveLosses > 0) {
    positionMultiplier *= Math.pow(0.8, consecutiveLosses) // 逐次减少仓位
  }
  
  // 基于市场状态调整
  if (features.volume_ratio > 2.0) {
    positionMultiplier *= 1.2 // 成交量放大时适度增加
  }
  
  return Math.max(3, Math.min(40, basePercent * positionMultiplier)) // 调整范围
}

const calculateAdaptiveStopLoss = (atr, multiplier) => {
  return atr * multiplier / 100
}

const calculateAdaptiveTakeProfit = (atr, confidence) => {
  const baseMultiplier = 2
  const confidenceMultiplier = confidence * 2
  return atr * (baseMultiplier + confidenceMultiplier) / 100
}

const checkMLStopConditions = (currentPrice, lastBuyPrice, adaptiveStopLoss, adaptiveTakeProfit) => {
  if (!lastBuyPrice) return false
  
  const stopLossPrice = lastBuyPrice * (1 - adaptiveStopLoss)
  const takeProfitPrice = lastBuyPrice * (1 + adaptiveTakeProfit)
  
  return currentPrice <= stopLossPrice || currentPrice >= takeProfitPrice
}

// 新增：策略性能分析函数
const calculateStrategyPerformance = (results) => {
  const trades = results.trades || []
  const signals = results.signals || []
  const equityCurve = results.equityCurve || []
  
  if (trades.length === 0) return {}
  
  // 信号质量分析
  const signalQuality = {
    totalSignals: signals.length,
    avgConfidence: signals.length > 0 ? signals.reduce((sum, s) => sum + (s.confidence || 0), 0) / signals.length : 0,
    strongSignals: signals.filter(s => s.confidence > 0.8).length,
    weakSignals: signals.filter(s => s.confidence < 0.6).length
  }
  
  // 交易效率分析
  const sellTrades = trades.filter(t => t.type === 'sell' && t.profit !== undefined)
  const profitableTrades = sellTrades.filter(t => t.profit > 0)
  
  const efficiency = {
    signalToTradeRatio: trades.length / Math.max(signals.length, 1),
    profitableTradeRatio: profitableTrades.length / Math.max(sellTrades.length, 1),
    avgHoldingPeriod: calculateAvgHoldingPeriod(trades),
    maxConsecutiveWins: calculateMaxConsecutive(sellTrades, true),
    maxConsecutiveLosses: calculateMaxConsecutive(sellTrades, false)
  }
  
  // 风险指标
  const riskMetrics = {
    maxDrawdown: calculateMaxDrawdownFromCurve(equityCurve),
    volatility: calculateEquityVolatility(equityCurve),
    riskAdjustedReturn: calculateRiskAdjustedReturn(equityCurve)
  }
  
  return {
    signalQuality,
    efficiency,
    riskMetrics,
    recommendation: generateStrategyRecommendation(signalQuality, efficiency, riskMetrics)
  }
}

// 辅助函数
const calculateAvgHoldingPeriod = (trades) => {
  const pairs = []
  let buyTrade = null
  
  for (const trade of trades) {
    if (trade.type === 'buy') {
      buyTrade = trade
    } else if (trade.type === 'sell' && buyTrade) {
      const buyDate = new Date(buyTrade.date)
      const sellDate = new Date(trade.date)
      pairs.push((sellDate - buyDate) / (1000 * 60 * 60 * 24)) // 天数
      buyTrade = null
    }
  }
  
  return pairs.length > 0 ? pairs.reduce((a, b) => a + b, 0) / pairs.length : 0
}

const calculateMaxConsecutive = (trades, isWin) => {
  let maxCount = 0
  let currentCount = 0
  
  for (const trade of trades) {
    const condition = isWin ? trade.profit > 0 : trade.profit <= 0
    if (condition) {
      currentCount++
      maxCount = Math.max(maxCount, currentCount)
    } else {
      currentCount = 0
    }
  }
  
  return maxCount
}

const calculateMaxDrawdownFromCurve = (equityCurve) => {
  if (equityCurve.length === 0) return 0
  
  let maxEquity = equityCurve[0].equity
  let maxDrawdown = 0
  
  for (const point of equityCurve) {
    maxEquity = Math.max(maxEquity, point.equity)
    const drawdown = (maxEquity - point.equity) / maxEquity
    maxDrawdown = Math.max(maxDrawdown, drawdown)
  }
  
  return maxDrawdown * 100
}

const calculateEquityVolatility = (equityCurve) => {
  if (equityCurve.length < 2) return 0
  
  const returns = []
  for (let i = 1; i < equityCurve.length; i++) {
    const ret = (equityCurve[i].equity - equityCurve[i-1].equity) / equityCurve[i-1].equity
    returns.push(ret)
  }
  
  const mean = returns.reduce((a, b) => a + b, 0) / returns.length
  const variance = returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / returns.length
  
  return Math.sqrt(variance) * 100
}

const calculateRiskAdjustedReturn = (equityCurve) => {
  if (equityCurve.length === 0) return 0
  
  const totalReturn = (equityCurve[equityCurve.length - 1].equity - equityCurve[0].equity) / equityCurve[0].equity
  const volatility = calculateEquityVolatility(equityCurve) / 100
  
  return volatility > 0 ? totalReturn / volatility : 0
}

const generateStrategyRecommendation = (signalQuality, efficiency, riskMetrics) => {
  const recommendations = []
  
  // 信号质量建议
  if (signalQuality.avgConfidence < 0.7) {
    recommendations.push('建议提高置信度阈值或调整特征权重')
  }
  
  if (signalQuality.totalSignals > 0 && signalQuality.weakSignals / signalQuality.totalSignals > 0.4) {
    recommendations.push('弱信号过多，考虑开启风险过滤器')
  }
  
  // 交易效率建议
  if (efficiency.profitableTradeRatio < 0.5) {
    recommendations.push('胜率较低，建议优化止损止盈参数')
  }
  
  if (efficiency.maxConsecutiveLosses > 5) {
    recommendations.push('连续亏损过多，建议开启动态仓位管理')
  }
  
  // 风险控制建议
  if (riskMetrics.maxDrawdown > 20) {
    recommendations.push('最大回撤过大，建议降低仓位或加强风险控制')
  }
  
  if (riskMetrics.volatility > 15) {
    recommendations.push('策略波动性较大，建议调整情绪指标权重')
  }
  
  return recommendations.length > 0 ? recommendations : ['策略表现良好，可继续使用']
}

// 获取历史数据
export const fetchHistoricalData = async (symbol, period, interval, dataSource) => {
  // 根据用户选择决定使用真实数据还是模拟数据
  if (dataSource === 'real') {
    try {
      // 尝试获取真实历史数据
      const realData = await fetchRealHistoricalData(symbol, period, interval)
      if (realData && realData.length > 0) {
        return realData
      }
    } catch (error) {
      console.warn('获取真实数据失败，使用模拟数据:', error.message)
    }
  }
  
  // 使用模拟数据
  return generateMockHistoricalData(symbol, period, interval)
}

// 获取真实历史数据
export const fetchRealHistoricalData = async (symbol, period, interval) => {
  const symbolMap = {
    'BTC/USDT': { binance: 'BTCUSDT', coingecko: 'bitcoin', cryptocompare: 'BTC' },
    'ETH/USDT': { binance: 'ETHUSDT', coingecko: 'ethereum', cryptocompare: 'ETH' },
    'BNB/USDT': { binance: 'BNBUSDT', coingecko: 'binancecoin', cryptocompare: 'BNB' },
    'SOL/USDT': { binance: 'SOLUSDT', coingecko: 'solana', cryptocompare: 'SOL' }
  }
  
  const coinInfo = symbolMap[symbol]
  if (!coinInfo) {
    throw new Error(`不支持的交易对: ${symbol}`)
  }
  
  // 转换周期为天数
  let days = 30
  if (period === '7d') days = 7
  else if (period === '30d') days = 30
  else if (period === '90d') days = 90
  else if (period === '1y') days = 365
  
  // 转换时间间隔
  let binanceInterval = '1d'
  if (interval === '1h') binanceInterval = '1h'
  else if (interval === '4h') binanceInterval = '4h'
  else if (interval === '1d') binanceInterval = '1d'
  
  // 优先使用Binance API（数据质量最高）
  try {
    const response = await axios.get('https://api.binance.com/api/v3/klines', {
      params: {
        symbol: coinInfo.binance,
        interval: binanceInterval,
        limit: Math.min(days, 1000) // Binance最多返回1000条数据
      },
      timeout: 15000
    })
    
    if (response.data && response.data.length > 0) {
      const data = response.data.map(item => ({
        date: new Date(item[0]).toISOString().split('T')[0],
        open: parseFloat(item[1]),
        high: parseFloat(item[2]),
        low: parseFloat(item[3]),
        close: parseFloat(item[4]),
        volume: parseFloat(item[5])
      }))
      
      console.log(`成功从 Binance 获取 ${data.length} 条数据`)
      return data
    }
  } catch (error) {
    console.warn('Binance API失败:', error.message)
  }
  
  // 备用：CryptoCompare API
  try {
    const response = await axios.get('https://min-api.cryptocompare.com/data/v2/histoday', {
      params: {
        fsym: coinInfo.cryptocompare,
        tsym: 'USD',
        limit: Math.min(days, 2000)
      },
      timeout: 15000
    })
    
    if (response.data && response.data.Data && response.data.Data.Data) {
      const data = response.data.Data.Data.map(item => ({
        date: new Date(item.time * 1000).toISOString().split('T')[0],
        open: item.open,
        high: item.high,
        low: item.low,
        close: item.close,
        volume: item.volumeto
      }))
      
      console.log(`成功从 CryptoCompare 获取 ${data.length} 条数据`)
      return data
    }
  } catch (error) {
    console.warn('CryptoCompare API失败:', error.message)
  }
  
  // 备用：CoinGecko API
  try {
    const response = await axios.get(`https://api.coingecko.com/api/v3/coins/${coinInfo.coingecko}/market_chart`, {
      params: {
        vs_currency: 'usd',
        days: days,
        interval: days > 90 ? 'daily' : 'daily'
      },
      timeout: 10000
    })
    
    if (response.data && response.data.prices) {
      return response.data.prices.map((item, index) => {
        const date = new Date(item[0]).toISOString().split('T')[0]
        const price = item[1]
        // CoinGecko只提供价格，我们需要模拟OHLC
        const variation = 0.02 // 2%的变化范围
        return {
          date,
          open: price * (1 + (Math.random() - 0.5) * variation),
          high: price * (1 + Math.random() * variation),
          low: price * (1 - Math.random() * variation),
          close: price,
          volume: 1000 + Math.random() * 2000
        }
      })
    }
  } catch (error) {
    console.warn('CoinGecko API失败:', error.message)
  }
  
  throw new Error('所有真实数据源都无法访问')
}

// 生成模拟历史数据（备用）
export const generateMockHistoricalData = (symbol, period, interval) => {
  const data = []
  const now = new Date()
  let days = 30
  
  if (period === '7d') days = 7
  else if (period === '30d') days = 30
  else if (period === '90d') days = 90
  else if (period === '1y') days = 365
  
  const basePrice = symbol === 'BTC/USDT' ? 45000 : 
                   symbol === 'ETH/USDT' ? 3000 : 
                   symbol === 'BNB/USDT' ? 400 : 150
  
  let currentPrice = basePrice
  let trend = 1 // 1为上涨趋势，-1为下跌趋势
  let trendDays = 0
  
  for (let i = 0; i < days; i++) {
    const date = new Date(now)
    date.setDate(date.getDate() - (days - i))
    
    // 每5-10天改变一次趋势
    if (trendDays > 5 + Math.random() * 5) {
      trend *= -1
      trendDays = 0
    }
    
    // 根据趋势调整价格
    const trendChange = trend * (0.005 + Math.random() * 0.015) // 0.5-2%的趋势变化
    const randomChange = (Math.random() - 0.5) * 0.01 // ±0.5%的随机波动
    
    currentPrice *= (1 + trendChange + randomChange)
    
    const open = currentPrice * (0.99 + Math.random() * 0.02)
    const close = currentPrice
    const high = Math.max(open, close) * (1 + Math.random() * 0.01)
    const low = Math.min(open, close) * (1 - Math.random() * 0.01)
    const volume = 500 + Math.random() * 1000
    
    data.push({
      date: date.toISOString().split('T')[0],
      open,
      high,
      low,
      close,
      volume
    })
    
    trendDays++
  }
  
  return data
}